package com.jeesite.modules.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 静态资源控制器
 * 处理头像和文件的静态资源访问
 */
@RestController
@Component
public class StaticResourceController {
    
    private static final Logger logger = LoggerFactory.getLogger(StaticResourceController.class);
    
    /**
     * 获取头像文件
     */
    @GetMapping({"/avatars/{filename:.+}", "/avatars/**"})
public ResponseEntity<byte[]> getAvatar(@PathVariable(required = false) String filename, HttpServletRequest request) {
    // 如果filename为null（通过/**匹配的路径），则从请求路径中提取
    if (filename == null) {
        String requestPath = request.getRequestURI();
        logger.info("请求路径: {}", requestPath);
        // 从/js/avatars/xxx.jpg提取文件名
        String prefix = "/js/avatars/";
        if (requestPath.startsWith(prefix)) {
            filename = requestPath.substring(prefix.length());
            logger.info("提取的文件名: {}", filename);
        } else {
            logger.warn("请求路径不匹配前缀: {} vs {}", requestPath, prefix);
            return ResponseEntity.notFound().build();
        }
    } else {
        logger.info("直接获取的文件名: {}", filename);
    }
        try {
            // 构建文件路径
            Path filePath = Paths.get("./userfiles/upload/avatars/" + filename);
            File file = filePath.toFile();
            
            if (!file.exists() || !file.isFile()) {
                logger.warn("头像文件不存在: {}", filename);
                return ResponseEntity.notFound().build();
            }
            
            // 读取文件内容
            byte[] fileContent = Files.readAllBytes(filePath);
            
            // 确定Content-Type
            String contentType = getContentType(filename);
            
            logger.debug("返回头像文件: {} ({})", filename, contentType);
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CACHE_CONTROL, "public, max-age=3600")
                    .body(fileContent);
                    
        } catch (Exception e) {
            logger.error("获取头像文件失败: {}", filename, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    /**
     * 获取普通文件
     */
    @GetMapping({"/files/{filename:.+}", "/files/**"})
public ResponseEntity<byte[]> getFile(@PathVariable(required = false) String filename, HttpServletRequest request) {
    // 如果filename为null（通过/**匹配的路径），则从请求路径中提取
    if (filename == null) {
        String requestPath = request.getRequestURI();
        // 从/js/files/xxx.jpg提取文件名
        String prefix = "/js/files/";
        if (requestPath.startsWith(prefix)) {
            filename = requestPath.substring(prefix.length());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
        try {
            // 构建文件路径
            Path filePath = Paths.get("./userfiles/upload/files/" + filename);
            File file = filePath.toFile();
            
            if (!file.exists() || !file.isFile()) {
                logger.warn("文件不存在: {}", filename);
                return ResponseEntity.notFound().build();
            }
            
            // 读取文件内容
            byte[] fileContent = Files.readAllBytes(filePath);
            
            // 确定Content-Type
            String contentType = getContentType(filename);
            
            logger.debug("返回文件: {} ({})", filename, contentType);
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(fileContent);
                    
        } catch (Exception e) {
            logger.error("获取文件失败: {}", filename, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    /**
     * 处理OPTIONS预检请求
     */
    @RequestMapping(value = {"/avatars/**", "/files/**"}, method = RequestMethod.OPTIONS)
    public ResponseEntity<Void> handleOptions() {
        // Global CORS configuration will handle OPTIONS; return 200
        return ResponseEntity.ok().build();
    }
    
    /**
     * 根据文件扩展名确定Content-Type
     */
    private String getContentType(String filename) {
        String extension = "";
        int lastDotIndex = filename.lastIndexOf('.');
        if (lastDotIndex > 0) {
            extension = filename.substring(lastDotIndex + 1).toLowerCase();
        }
        
        switch (extension) {
            case "png":
                return MediaType.IMAGE_PNG_VALUE;
            case "jpg":
            case "jpeg":
                return MediaType.IMAGE_JPEG_VALUE;
            case "gif":
                return MediaType.IMAGE_GIF_VALUE;
            case "webp":
                return "image/webp";
            case "svg":
                return "image/svg+xml";
            case "pdf":
                return MediaType.APPLICATION_PDF_VALUE;
            case "txt":
                return MediaType.TEXT_PLAIN_VALUE;
            case "json":
                return MediaType.APPLICATION_JSON_VALUE;
            default:
                return MediaType.APPLICATION_OCTET_STREAM_VALUE;
        }
    }
}